package com.imooc.controller;

import com.imooc.service.ItemESService;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("items")
public class ItemsController {

    @Autowired
    private ItemESService itemESService;

    @GetMapping("/hello")
    public Object hello() {
        return "Hello Elasticsearch!";
    }

    @GetMapping("/es/search")
    public IMOOCJSONResult search(
            String keywords,
            String sort,
            Integer page,
            Integer pageSize) {
        //如果keywords为空我们这不进行搜索,也可以默认搜索全部
        if (StringUtils.isBlank(keywords)) {
            return IMOOCJSONResult.errorMsg("传入的是null");
        }
        if (page == null) {
            page = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        //注意,这里执行分页的时候es是从0开始的
        page--;
        PagedGridResult grid = itemESService.searchItems(keywords, sort, page, pageSize);
        return IMOOCJSONResult.ok(grid);
    }

}